package org.hhq.demo.config.predicate;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.List;
import java.util.function.Predicate;
@Slf4j
@Component
public class RequestMethodsRoutePredicateFactory extends AbstractRoutePredicateFactory<RequestMethodsRoutePredicateFactory.RequestMethodsConfig> {

    public RequestMethodsRoutePredicateFactory() {
        super(RequestMethodsConfig.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(RequestMethodsConfig config) {
        return ((param)-> {
            log.info("config.methods:{},method:{}",config.methods,param.getRequest().getMethod().name());
            if (!CollectionUtils.isEmpty(config.methods) && config.methods.stream().anyMatch(method->method.equalsIgnoreCase(param.getRequest().getMethod().name()))){
                return true;
            }
            return false;
        });
    }

    @Data
    static class RequestMethodsConfig{
        private List<String> methods;
    }
}
